<script lang="ts" setup name="Trademark">
import { ref, reactive, onMounted, nextTick } from 'vue'
// 引入增删改查接口
import { getTradeMarkList, addTradeMark, updateTradeMark, deleteTradeMark } from '@/api/product/trademark/index'
// 引入自定义的ts数据类型
import type { TradeMarkResponseData, TradeMarkList, TradeMark } from '@/api/product/trademark/type'
// 引入element 定义的类型
import type { UploadProps } from 'element-plus'
import { ElMessage } from 'element-plus'

// loading效果
let loading = ref<boolean>(false)
// 表格数据
let tableData = reactive<TradeMarkList>([])
// 每页多少条
const pageSize = ref<number>(5)
// 当前多少页
const pageNo = ref<number>(1)
// 一共多少条
const total = ref<number>(0)
// pageSize更改事件
const handleSizeChange = (val: number) => {
  pageSize.value = val
  getList()
}

// 获取列表数据
const getList = async (PageNo = 1) => {
  pageNo.value = PageNo
  loading.value = true
  let result: TradeMarkResponseData = await getTradeMarkList(pageNo.value, pageSize.value)
  if (result.code == 200) {
    total.value = result.data.total
    tableData = result.data.records
    loading.value = false
  }
}
onMounted(() => {
  getList()
})
// 对话框
let dialogVisible = ref<boolean>(false)

// 编辑按钮事件
const handleEdit = (row: TradeMark) => {
  nextTick(() => {
    formRef.value.clearValidate('tmName')
    formRef.value.clearValidate('logoUrl')
  })
  Object.assign(trademarkFrom, row)
  dialogVisible.value = true
}

// 删除按钮事件
const handleDelete = async (id: number) => {
  let result = await deleteTradeMark(id)
  if (result.code == 200) {
    // 删除成功
    ElMessage({
      type: 'success',
      message: '删除品牌成功'
    })
    getList(pageNo.value)
  } else {
    // 删除失败
    ElMessage({
      type: 'error',
      message: '删除品牌失败'
    })
  }
}

// 新增/编辑表单
let trademarkFrom = reactive<TradeMark>({
  tmName: '',
  logoUrl: ''
})

//获取el-form组件实例
let formRef = ref();

//品牌自定义校验规则方法
const validatorTmName = (rule: any, value: any, callBack: any) => {
  //是当表单元素触发blur时候,会触发此方法
  //自定义校验规则
  if (value.trim().length >= 2) {
    callBack();
  } else {
    //校验未通过返回的错误的提示信息
    callBack(new Error('品牌名称位数大于等于两位'))
  }
}
//品牌LOGO图片的自定义校验规则方法
const validatorLogoUrl = (rule: any, value: any, callBack: any) => {
  //如果图片上传
  if (value) {
    callBack();
  } else {
    callBack(new Error('LOGO图片务必上传'))
  }
}
//表单校验规则对象
const rules = {
  tmName: [
    //required:这个字段务必校验,表单项前面出来五角星
    //trigger:代表触发校验规则时机[blur、change]
    { required: true, trigger: 'blur', validator: validatorTmName }
  ],
  logoUrl: [
    { required: true, validator: validatorLogoUrl }
  ]
}

// 新增品牌按钮事件
const addTrademark = () => {
  // 新增/编辑表单
  trademarkFrom = {
    tmName: '',
    logoUrl: ''
  }
  dialogVisible.value = true
}

// 取消按钮
const cancel = () => {
  dialogVisible.value = false
}

// 提交按钮
const submitTrademark = async () => {
  let result

  //在你发请求之前,要对于整个表单进行校验
  //调用这个方法进行全部表单相校验,如果校验全部通过，在执行后面的语法
  await formRef.value.validate();
  // 有id为修改
  if (trademarkFrom.id) {
    result = await updateTradeMark(trademarkFrom)
  } else {
    // 无id为新增
    result = await addTradeMark(trademarkFrom)
  }
  if (result.code == 200) {
    //关闭对话框
    dialogVisible.value = false;
    //弹出提示信息
    ElMessage({
      type: 'success',
      message: trademarkFrom.id ? "修改品牌成功" : '添加品牌成功'
    });
    getList(trademarkFrom.id ? pageNo.value : 1)
  } else {
    //添加品牌失败
    ElMessage({
      type: 'error',
      message: trademarkFrom.id ? "修改品牌失败" : '添加品牌失败'
    });
    //关闭对话框
    dialogVisible.value = false;
  }
}


// 定义允许上传的文件类型
const allFileType = ['png', 'jpeg', 'gif']
// 允许上传的文件大小  单位 1kb = 1024, 1M = 1024kb
let FileSize = 4  //这里文件大小是4M
// 图片上传前
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  const { type, size } = rawFile
  // 当前上传的文件类型
  let filetype = type.slice(6, type.length)
  // 当前上传的文件大小
  let filesize = size / 1021 / 1024
  if (allFileType.indexOf(filetype) > 0) {
    if (filesize < FileSize) {
      return true
    } else {
      ElMessage({
        type: 'error',
        message: `上传文件大小小于${FileSize}M`
      })
      return false;
    }
  } else {
    let allType = allFileType.join(' | ')
    ElMessage({
      type: 'error',
      message: `上传文件格式务必为 ${allType} 类型`
    })
    return false;
  }
}

//图片上传成功钩子
const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  //response:即为当前这次上传图片post请求服务器返回的数据
  //收集上传图片的地址,添加一个新的品牌的时候带给服务器
  trademarkFrom.logoUrl = response.data;
  //图片上传成功,清除掉对应图片校验结果
  formRef.value.clearValidate('logoUrl');
}


</script>

<template>
  <div>
    <el-card>
      <el-button type="primary" size="default" icon="Plus" @click="addTrademark">添加品牌</el-button>
      <el-table v-loading="loading" :data="tableData" style="margin:10px 0px" border>
        <el-table-column label="序号" width="80px" align="center" type="index" />
        <el-table-column prop="tmName" label="品牌名称" />
        <el-table-column label="品牌LOGO" align="center">
          <template #="{ row, $index }">
            <el-image style="width:80px;height: 80px;" :src="row.logoUrl" fit="fill">
              <!-- 当图片加载失败时设置默认图片 -->
              <template #error>
                <img src="https://img2.baidu.com/it/u=1303864403,607087645&fm=253&fmt=auto&app=138&f=JPEG?" alt=""
                  style="width:80px;height: 80px;">
              </template>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column label="品牌操作" min-width="120">
          <template #="{ row, $index }">
            <el-button type="primary" size="small" icon="Edit" @click="handleEdit(row)">编辑</el-button>
            <!-- <el-button type="danger" size="small" icon="Delete">删除</el-button> -->
            <el-popconfirm :title="`您确定要删除${row.tmName}?`" width="250px" icon="Delete" @confirm='handleDelete(row.id)'>
              <template #reference>
                <el-button type="primary" size="small" icon="Delete"></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination v-model:current-page="pageNo" v-model:page-size="pageSize" :page-sizes="[5, 10, 25, 100]"
        layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
        @current-change="getList" />
    </el-card>

    <el-dialog v-model="dialogVisible" :title="trademarkFrom.id ? '修改品牌' : '添加品牌'" width="500">
      <el-form style="width: 80%;" :model="trademarkFrom" :rules="rules" ref="formRef">
        <el-form-item label="品牌名称" label-width="100px" prop="tmName">
          <el-input placeholder="请您输入品牌名称" v-model="trademarkFrom.tmName"></el-input>
        </el-form-item>
        <el-form-item label="品牌LOGO" label-width="100px" prop="logoUrl">
          <!-- upload组件属性:action图片上传路径书写/api,代理服务器不发送这次post请求  -->
          <el-upload class="avatar-uploader" action="/api/admin/product/fileUpload" :show-file-list="false"
            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="trademarkFrom.logoUrl" :src="trademarkFrom.logoUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <!-- 具名插槽:footer -->
      <template #footer>
        <el-button type="primary" size="default" @circle="cancel">取消</el-button>
        <el-button type="primary" size="default" @click="submitTrademark">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
